package com.smedi.ismedi.web.starter.exception;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

@Slf4j
@Data
public class LogicException extends RuntimeException {
    private String code;

    // 异常信息
    private String errorMsg;

    // Exception 具体信息
    private Object exception;

    public LogicException(ErrorItem errorItem) {
        super(errorItem.getMessage());
        this.code = errorItem.getCode();
        this.errorMsg = errorItem.getMessage();
    }

    public LogicException(ErrorItem errorItem, Exception e) {
        super(errorItem.getMessage() + " [错误消息：" + e.getMessage() + "]");
        this.code = errorItem.getCode();
        this.errorMsg = errorItem.getMessage();
        this.exception = e;
        log.error("exception >>> {}", e);
    }

    public LogicException(ErrorItem errorItem, String application, String message) {
        super(errorItem.getMessage() + (StringUtils.isEmpty(application)
                ? " [错误消息：" + message + "]"
                : " [调用服务 -> " + application + "，错误消息：" + message + "]"));

        this.code = errorItem.getCode();
        this.errorMsg = errorItem.getMessage() + (StringUtils.isEmpty(application)
                ? " [错误消息：" + message + "]"
                : " [调用服务 -> " + application + "，错误消息：" + message + "]");
    }

    // 抛出逻辑异常
    public static LogicException raise(ErrorItem errorItem) {
        return new LogicException(errorItem);
    }

    // 排除逻辑异常，并且带消息
    public static LogicException raise(ErrorItem errorItem, Exception e) {
        return new LogicException(errorItem, e);
    }

    // 排除逻辑异常，并且带消息
    // 这类错误消息一般用于调用内部服务时的抛错信息
    public static LogicException raise(ErrorItem errorItem, String application, String message) {
        return new LogicException(errorItem, application, message);
    }

    public static LogicException raise(ErrorItem errorItem, Object... args) {
        return new LogicException(new ErrorItem(1, String.format(errorItem.getMessage(), args)));
    }
}